package com.foreveross.bsl.mam.device.application.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Named;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import com.foreveross.bsl.common.utils.bean.BeanHelper;
import com.foreveross.bsl.mam.device.application.DeviceApplication;
import com.foreveross.bsl.mam.device.application.vo.DeviceVO;
import com.foreveross.bsl.mam.model.device.domain.Device;

/**
 * 设备管理实现
 * @author tanzhixiong
 * @2013-6-21 @下午4:41:43
 */
@Named("deviceApplication")
public class DeviceApplicationImpl implements DeviceApplication{

	@Override
	public DeviceVO saveEntity(DeviceVO entity) {
		Device device = new Device();
		BeanHelper.copyProperties(device, entity);
		device.save();
		entity.setId(device.getId());
		return entity;
	}

	@Override
	public DeviceVO updateEntity( String id, DeviceVO entity) {
		Device device = new Device();
		device = (Device)device.findOne(id);
		BeanHelper.copyProperties(device, entity);
		device.save();
		BeanHelper.copyProperties(entity, device);
		return entity;
	}

	@Override
	public void deleteEntity( String id) {
		Device device = new Device();
		device = (Device) device.findOne(id);
		device.delete();
	}

	@Override
	public DeviceVO getEntity( String id) {
		Device device = new Device();
		device = (Device) device.findOne(id);
		DeviceVO devicevo = new DeviceVO();
		BeanHelper.copyProperties(devicevo, device);
		return devicevo;
	}

	@Override
	public List<DeviceVO> findAll() {
		Device device = new Device();
		Iterable iterable = device.findAll();
		if(iterable != null){
			List<DeviceVO> result = new ArrayList<DeviceVO>();
			DeviceVO vo;
			for (Iterator iterator = iterable.iterator(); iterator.hasNext();) {
				Device obj = (Device) iterator.next();
				vo = new DeviceVO();
				BeanHelper.copyProperties(vo, obj);
				result.add(vo);
			}
			return result;
		}
		return null;
	}

	@Override
	public Page<DeviceVO> findByPageable(Pageable pageable) {
		Device device = new Device();
		Page page = device.findAll(pageable);
		if(page != null && page.getContent() != null){
			List<DeviceVO> result = new ArrayList<DeviceVO>();
			DeviceVO vo;
			for (Iterator iterator = page.getContent().iterator(); iterator.hasNext();) {
				Device obj = (Device) iterator.next();
				vo = new DeviceVO();
				BeanHelper.copyProperties(vo, obj);
				result.add(vo);
			}
			Page<DeviceVO> pageVO = new PageImpl<DeviceVO>(result, pageable, page.getTotalElements());
			return pageVO;
		}
		return null;
	}



}
